package com.cedifie.lendapp.ui.user.act

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActUserFeedbackBinding
import com.cedifie.lendapp.databinding.ItemQuestionTypeBinding
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.ApiService.addCommonParams
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpAct
import com.cedifie.lendapp.ui.user.adapter.CedUserFeedbackImageAdapter
import com.cedifie.lendapp.ui.user.impl.CedUserFeedbackPresenterImpl
import com.cedifie.lendapp.ui.user.view.ICedUserFeedbackView
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.imagecovert.ImageConvert
import com.cedifie.lib_baseadapter.CEDOnItemChildClickListener
import com.lib.base.utils.log.LogHelper
import org.json.JSONObject
import java.io.File


/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:45
 * @Annotation：意见反馈
 */
class CedUserFeedbackAct: MvpAct<ICedUserFeedbackView, CedUserFeedbackPresenterImpl>(), ICedUserFeedbackView {

    lateinit var binding: ActUserFeedbackBinding
    //图片列表
    var mImgAdapter: CedUserFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_NUM = "num"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, CedUserFeedbackAct::class.java)
            intent.putExtra(INTENT_KEY_STAR_NUM, count)
            context.startActivity(intent)
        }
    }

    override fun getCedRootView(): View {
        binding = ActUserFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): CedUserFeedbackPresenterImpl {
        return CedUserFeedbackPresenterImpl(getContext())
    }

    override fun initCedView() {
        setCedTitleBarVisibility(View.VISIBLE)
        setCedTextTitle(getString(R.string.personal_complaints_suggestions))
        setCedTextTitleGravity(Gravity.CENTER)
        setCedRightBtnVisibility(View.GONE)

        initCedRecyclerView()
        binding.tvLength.text = "0/1000"

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                LogHelper.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    LogHelper.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (mImgAdapter?.itemCount == 3){
                            mImgAdapter?.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        mImgAdapter?.addLastItem(imgObj)

                        mvpPresenter?.uploadCedImageAction(localPath)
                    }
                }

            } else {
                LogHelper.e("No media selected")
            }
        }
    }

    override fun initCedListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER,"UserFeedback Page")
        }
        //输入框监听
        binding.editRemark.addTextChangedListener(IEditChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                HttpHelper.addCedEventAction(CedEventType.FORM.CED_FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }
        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showCedToast(getString(R.string.feedback_please_select_question_type))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showCedToast(getString(R.string.feedback_briefly_hint))
                return@setOnClickListener
            }
            showCedLoading(getString(R.string.loading))
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.CED_API_FEEDBACK_SUBMIT_PATH)
                put("type",getSelectTypeItem()?.optString("value"))//反馈类型
                put("opinion",remark)//反馈内容
            }
            val imgUrls = getImageUrls()
            if (imgUrls.isNotEmpty()){
                params.put("images",imgUrls)
            }
            val starCount = getFeedbackStartNum()
            if (starCount.isNotEmpty()){
                params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
            }

            mvpPresenter?.submitCedFeedbackAction(params)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_FEEDBACK_SUBMIT,"")
        }
    }

    override fun initCedData() {
        mvpPresenter?.loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        mImgAdapter?.addFirstItem(imgObj)
    }

    /**
     * 初始化图片列表
     */
    private fun initCedRecyclerView() {
        binding.recyclerView.setHasFixedSize(false)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        mImgAdapter = CedUserFeedbackImageAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mImgAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mImgAdapter?.setOnItemChildClickListener(CEDOnItemChildClickListener { parent, childView, position ->
            mImgAdapter?.let {
                val item = it.getItem(position)
                when(childView.id){
                    R.id.ivDelete -> {//删除
                        if (!item.optBoolean("isDefault")){
                            it.removeItem(position)

                            //是否需要添加默认图片
                            var isAddDefault = true
                            for (i in 0..< it.itemCount){
                                if (it.getItem(i).optBoolean("isDefault")){
                                    isAddDefault = false
                                    break
                                }
                            }
                            if (isAddDefault){
                                val imgObj = JSONObject()
                                imgObj.put("isDefault",true)
                                mImgAdapter?.addFirstItem(imgObj)
                            }
                        }
                    }
                    R.id.ivImage -> {//选择图片
                        if (item.optBoolean("isDefault")){
                            hasRequestPermissions()
                        }
                    }
                }
            }
        })
    }


    private val IEditChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
            binding.tvLength.text = "$textLength/1000"
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun setQuestionTypeList(){
        binding.flexboxLayout.removeAllViews()
        val typeList = mvpPresenter?.getTypeList()
        typeList?.let { list ->
            for (i in 0..< list.size) {
                val item = list[i]
                val itemBinding = ItemQuestionTypeBinding.inflate(layoutInflater)
                itemBinding.textView.text = item.optString("title")
                if (item.optBoolean("isSelect")){
                    itemBinding.textView.setTextColor(ContextCompat.getColor(this,R.color.white))
                    itemBinding.textView.setBackgroundResource(R.drawable.btn_background)
                } else {
                    itemBinding.textView.setTextColor(Color.parseColor("#FF6E6E6E"))
                    itemBinding.textView.setBackgroundResource(R.drawable.ced_circle_fill_fff8f8f8)
                }
                binding.flexboxLayout.addView(itemBinding.root)
                itemBinding.textView.setOnClickListener {
                    if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                        return@setOnClickListener
                    }
                    for (index in 0..< list.size){
                        val obj = list[index]
                        if (index == i){
                            obj.put("isSelect",true)
                            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_FEEDBACK_QUESTION_TYPE,obj.optString("title"))
                        } else {
                            obj.put("isSelect",false)
                        }
                    }
                    setQuestionTypeList()
                }
            }
        }
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        for (i in 0..<mvpPresenter.getTypeList().size){
            val obj = mvpPresenter.getTypeList()[i]
            if (obj.optBoolean("isSelect")){
                selectItem = obj
                break
            }
        }
        return selectItem
    }


    /**
     * 获取上传的图片链接
     */
    private fun getImageUrls(): String{
        var imgUrls = ""
        mImgAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isDefault")){
                    continue
                }
                imgUrls = imgUrls + item.optString("imgUrl") + ","
            }
        }
        if (imgUrls.isNotEmpty()){
            imgUrls = imgUrls.substring(0,imgUrls.length - 1)
        }
        return imgUrls
    }

    /**
     * 获取评分数量
     */
    private fun getFeedbackStartNum(): String {
        if (intent.extras == null){
            return ""
        }
        return if (intent.extras?.getString(INTENT_KEY_STAR_NUM) == null) "" else intent.extras?.getString(INTENT_KEY_STAR_NUM).toString()
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun setCedQuestionTypeList(typeList: ArrayList<JSONObject>) {
        setQuestionTypeList()
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showCedUploadImageSuccess(imgUrl: String) {
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        val lastItem = mImgAdapter?.lastItem
        lastItem?.put("imgUrl",imgUrl)
        destinationDirectory?.let {
            if (it.isFile){
                destinationDirectory?.delete()
            }
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showCedSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_USER_FEEDBACK_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_USER_FEEDBACK_END,"")
    }
}